Python Crash Course-note4

-if语句


if语句
示例程序

1
2
3
4
5
6
7
8
9
10
cars=['absore',bmw','core']
for car in cars:
if car=='bmw':
print(car.upper())
else
print(car.titile())
//输出
Absore
BMW
Core

循环检查当前car是否为bmw,是则全大写打印,否则首字母大写打印。

条件测试
python检查是否相等时区分大小写。
如果大小写无关紧要,而只想检查变量的值,可将变量的值转换为小写,在进行比较。

1
2
3
4
5
6
7
8
9
10
11
12
car='Audi'
if car.lower()=='audi':
print("true")
//输出true
```
**检查不相等**
要检查不相等,使用不等运算符!=即可,用法与其他语言无异。
**检查多个条件**
**与**:and---等价于C++的&&运算符
**或**:or---等价于C++的||

age=19
if age>18 and age>17:
print(“true”)
if age>18 or age>19:
print(“true”)
//output
true
true

1
2
3
4
**检查特定值是否在列表中**
**关键字in**:判断在列表中
**关键中not in**:判断不在列表中

al=[‘a’,’b’,’c’,’d’]
A = ‘a’
E= ‘e’
if A in al:
print(“true”)
if E not in al:
print(“true”)
//output
true
true

1
2
**if-elif-else结构**

age=19
if age<18: 28="" print("young")="" elif="" age<28:="" print("28")="" else:="" print("old")="" output=""

1
2
**列表判空**

age=[]
if age:
print(“not empty”)
else:
print(“empty”)
//output
empty
```


Thanks for your reward!